#import "sms_item.h"
#include <memory>

using namespace std;
using namespace sbrush;

@implementation SmsItem

- (id) init {
	self = [super init];
	if (self != nil) {
		_spectralModel = NULL;
	}
	return self;
}

- (id)initFromExisting:(FileItem *)fileItem {
	self = [super initFromExisting:fileItem];
	if (self != nil) {
		_spectralModel = NULL;
	}
	return self;
}

- (id)initFromFileItem:(FileItem*)fileItem
			 withModel:(sbrush::SpectralModel*)spectModel {
	self = [super initFromExisting:fileItem];
	if (self != nil) {
		_spectralModel = spectModel;
	}
	return self;
}

- (void) dealloc {
	delete _spectralModel;
	[super dealloc];
}

- (sbrush::SpectralModel*) spectralModel {
	return _spectralModel;
}

- (void) setSpectralModel:(sbrush::SpectralModel*)spectralModel {
	delete _spectralModel;
	_spectralModel = spectralModel;
}

- (BOOL)writeToFile:(NSError**)anError {
	if (_spectralModel == NULL) {
		if (anError != NULL) {
			*anError = [FileItem errorWithDescription:@"cannot save null object"
											errorCode:-3 
											 filePath:[self path]];
		}
		return NO;
	}
	try {
		_spectralModel->write([[self path] UTF8String]);
	}
	catch (...) {
		if (anError != NULL) {
			*anError = [FileItem errorWithDescription:@"failed to write spectral model"
											errorCode:-2 
											 filePath:[self path]];
		}
		return NO;
	}
	
	[self setSaved:YES];
	return YES;
}

- (BOOL)readFromFile:(NSError**)anError {
	auto_ptr<SpectralModel> model(NULL);
	try {
		model = SpectralModel::read([[self path] UTF8String]);
	}
	catch (...) {
		if (anError != NULL) {
			*anError = [FileItem errorWithDescription:@"failed to load spectral model"
											errorCode:-1 
											 filePath:[self path]];
		}
		[self setSaved:NO];
		return NO;
	}
	
	[self setSpectralModel:model.release()];
	[self setSaved:YES];
	return YES;
}


@end
